package com.situ.mall.admin.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.situ.mall.admin.pojo.dto.AdminLoginDTO;
import com.situ.mall.admin.pojo.dto.AdminPasswordDTO;
import com.situ.mall.admin.pojo.query.AdminQuery;
import com.situ.mall.admin.service.IAdminService;
import com.situ.mall.common.util.CommonUtil;
import com.situ.mall.common.util.JwtUtil;
import com.situ.mall.common.util.Result;
import com.situ.mall.pojo.entity.admin.Admin;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author Sun Huijuan
 * @since 2024-10-09
 */
@RestController
@RequestMapping("/admin")
public class AdminController {
	
	@Autowired
	private IAdminService adminService;
	
	@Autowired
	private RedisTemplate redisTemplate;
	
	//Restful  GET（查找）、POST（添加）、DELETE（删除）、PUT（修改）
//	@RequestMapping("/list")method不写表示默认支持所有
//	@RequestMapping(value = "/list",method = {RequestMethod.GET,RequestMethod.POST})
//	@RequestMapping(value = "/list",method = RequestMethod.GET) 等同于下方写法
	@GetMapping("/list")
	public Result list(AdminQuery adminQuery) {
		IPage<Admin> page = new Page<>(adminQuery.getPage(), adminQuery.getLimit());
		QueryWrapper<Admin> queryWrapper = new QueryWrapper<>();
		queryWrapper.like(!ObjectUtils.isEmpty(adminQuery.getName()), "name", adminQuery.getName());
		queryWrapper.like(!ObjectUtils.isEmpty(adminQuery.getPhone()), "phone", adminQuery.getPhone());
		queryWrapper.between(!ObjectUtils.isEmpty(adminQuery.getBeginUpdateTime())&&!ObjectUtils.isEmpty(adminQuery.getEndUpdateTime()),
				"update_time",adminQuery.getBeginUpdateTime(),adminQuery.getEndUpdateTime());
		adminService.page(page, queryWrapper);
		Map<String, Object> map = new HashMap<>();
		map.put("total", page.getTotal());
		map.put("list", page.getRecords());
		return Result.ok(map);
	}
	
	//  /admin/deleteById?id=1
	//  /admin/deleteById/1
//	@DeleteMapping("/deleteById")
	@DeleteMapping("/deleteById/{id}")
	public Result deleteById(@PathVariable Integer id) {
		adminService.removeById(id);
		return Result.ok("删除成功！");
	}
	
	@DeleteMapping("/deleteAll/{ids}")
	public Result deleteAll(@PathVariable Integer[] ids) {
		adminService.removeByIds(Arrays.asList(ids));
		return Result.ok("删除成功！");
	}
	
	// @RequestBody：封装前台传递过来的JSON格式数据
	// @ResponseBody：将数据转换为JSON格式返回
	@PostMapping("/add")
	public Result add(@RequestBody Admin admin) {
		adminService.save(admin);
		return Result.ok("添加成功！");
	}
	
	@GetMapping("/selectById/{id}")
	public Result selectById(@PathVariable Integer id) {
		Admin admin = adminService.getById(id);
		return Result.ok(admin);
	}
	
	@PutMapping("/update")
	public Result update(@RequestBody Admin admin) {
		//adminService.updateById(admin);
		adminService.saveOrUpdate(admin);
		return Result.ok("修改成功！");
	}
	
	@PostMapping("/login")
	public Result login(@RequestBody AdminLoginDTO adminLoginDTO, HttpServletRequest request) {
		//判断验证码是否正确
		String captcha = (String) redisTemplate.opsForValue().get(CommonUtil.getCaptchaKey(request));
		//判断验证码是否有效
		if(StringUtils.isEmpty(captcha)){
			return Result.error("验证码已失效");
		}
		if(!captcha.equalsIgnoreCase(adminLoginDTO.getCaptcha())){
			return Result.error("验证码错误！");
		}
		QueryWrapper<Admin> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("name", adminLoginDTO.getName());
		//根据用户名查询用户
		Admin loginAdmin = adminService.getOne(queryWrapper);
		//用户名不存在
		if (loginAdmin == null) {
			return Result.error("用户名不存在！");
		}
		//判断密码是否正确
		if (!adminLoginDTO.getPassword().equalsIgnoreCase(loginAdmin.getPassword())){
			return Result.error("密码错误！");
		}
		if(loginAdmin.getStatus()==0){
			return Result.error("该用户被禁用");
		}
		//登录成功
		//构建Token
		Map<String,Object> map=new HashMap<>();
		map.put("id",loginAdmin.getId());
		map.put("name",loginAdmin.getName());
		String token = JwtUtil.createToken(map);
		return Result.ok("登录成功", token);
		
	}
	
	@GetMapping("/adminInfo")
	public Result adminInfo(@RequestHeader(name = "Authorization")String token) {
		String name = (String) JwtUtil.parseToken(token).get("name");
		QueryWrapper queryWrapper = new QueryWrapper();
		queryWrapper.eq("name", name);
		Admin admin = adminService.getOne(queryWrapper);
		return Result.ok(admin);
	}
	
	@PutMapping("/updateStatus/{id}/{status}")
	public Result updateStatus(@PathVariable Integer id, @PathVariable Integer status){
		//方法1：封装对象
		/*Admin admin=new Admin();
		admin.setId(id);
		admin.setStatus(status);
		adminService.updateById(admin);*/
		//方法2：传参
		UpdateWrapper<Admin> updateWrapper=new UpdateWrapper<>();
		updateWrapper.eq("id",id).set("status",status);
		adminService.update(updateWrapper);
		return Result.ok("修改成功！");
	}
	
	@PutMapping("/resetPassword")
	public Result resetPassword(@RequestBody AdminPasswordDTO adminPasswordDTO,
								@RequestHeader(name = "Authorization")String token){
		Map<String,Object> map=JwtUtil.parseToken(token);
		Integer id=(Integer)map.get("id");
		QueryWrapper queryWrapper = new QueryWrapper();
		queryWrapper.eq("id", id);
		queryWrapper.eq("password",adminPasswordDTO.getOldPassword());
		Admin admin = adminService.getOne(queryWrapper);
		if(admin==null){
			return Result.error("原密码错误！");
		}
		UpdateWrapper<Admin> updateWrapper=new UpdateWrapper<>();
		updateWrapper.eq("id",id).set("password",adminPasswordDTO.getNewPassword());
		adminService.update(updateWrapper);
		return Result.ok("修改成功！");
	}
}

